# -------------------------------
# 使用 PCA 对销售数据进行降维
# -------------------------------

import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt

# 1. 读取数据
file_path = "/mnt/data/sales_data_sample.csv"
df = pd.read_csv(file_path, encoding='latin1', engine='python')

# 2. 提取数值型数据
df_numeric = df.select_dtypes(include=[np.number]).dropna()

# 检查是否有可用数值列
if df_numeric.shape[1] == 0:
    raise ValueError("数据中没有数值列，请检查 CSV 文件内容。")

# 3. 标准化数据（均值0、方差1）
scaler = StandardScaler()
X_scaled = scaler.fit_transform(df_numeric)

# 4. PCA降维到2维
pca = PCA(n_components=2)
X_pca = pca.fit_transform(X_scaled)

# 5. 打印结果
print("原始维度：", X_scaled.shape[1])
print("降维后维度：", X_pca.shape[1])
print("解释方差比例：", pca.explained_variance_ratio_)
print("累计解释方差：", np.sum(pca.explained_variance_ratio_))

# 6. 将降维结果保存为CSV文件
df_pca = pd.DataFrame(X_pca, columns=['PC1', 'PC2'])
output_path = "/mnt/data/sales_data_sample_PCA_2D.csv"
df_pca.to_csv(output_path, index=False)
print(f"PCA降维结果已保存为: {output_path}")

# 7. 可视化（2D散点图）
plt.figure(figsize=(6,5))
plt.scatter(X_pca[:,0], X_pca[:,1], alpha=0.6)
plt.title("PCA 2D Projection of sales_data_sample.csv")
plt.xlabel("Principal Component 1")
plt.ylabel("Principal Component 2")
plt.grid(True)
plt.tight_layout()
plt.show()